<template>
    <div class="container">
        <Breadcrumb :items="['menu.sys', 'menu.sys.vipSolution']" />
        <a-card :title="$t('menu.sys.vipSolution')">
            <a-space fill direction="vertical">
                <a-row :gutter="16">
                    <a-col :span="12">
                        <a-space fill>
                            <a-button type="primary" @click="openModal()" shape="round">
                                <template #icon><icon-plus /></template>
                                添加方案
                            </a-button>
                            <a-button type="outline" @click="openVipDetailModal()" shape="round">
                                <template #icon><icon-settings /></template>
                                管理VIP权益内容
                            </a-button>
                        </a-space>
                    </a-col>
                    <a-col :flex="1">
                        <a-space align="end" style="justify-content: flex-end;" fill>
                            <a-button shape="circle" @click="fetchData">
                                <template #icon><icon-refresh /></template>
                            </a-button>
                        </a-space>
                    </a-col>
                </a-row>

                <a-table :data="renderData" :loading="loading" :bordered="{ cell: true }" :pagination="pagination"
                    @page-change="onPageChange" @page-size-change="onPageSizeChange">
                    <template #columns>
                        <a-table-column title="ID" data-index="id" :width="80" />
                        <a-table-column title="方案名称" data-index="name" />
                        <a-table-column title="图片" data-index="image" :width="80">
							<template #cell="{ record }">
								<a-image :src="record.image_url" width="40" height="40" />
							</template>
						</a-table-column>
                        <a-table-column title="方案描述" data-index="description" />
                        <a-table-column title="金额" data-index="money" :width="120">
                            <template #cell="{ record }">
                                ¥{{ record.money }}
                            </template>
                        </a-table-column>
                        <a-table-column title="天数" data-index="days" :width="100">
                            <template #cell="{ record }">
                                {{ record.days }}天
                            </template>
                        </a-table-column>
                        <a-table-column title="状态" data-index="status" :width="100">
                            <template #cell="{ record }">
                                <a-tag :color="record.status === 'online' ? 'green' : 'red'">
                                    {{ record.status === 'online' ? '上线' : '下线' }}
                                </a-tag>
                            </template>
                        </a-table-column>
                        <a-table-column title="创建时间" data-index="created_at" :width="180">
                            <template #cell="{ record }">
                                {{ formatTime(record.created_at) }}
                            </template>
                        </a-table-column>
                        <a-table-column title="更新时间" data-index="updated_at" :width="180">
                            <template #cell="{ record }">
                                {{ formatTime(record.updated_at) }}
                            </template>
                        </a-table-column>
                        <a-table-column title="操作" align="center" :width="120" fixed="right">
                            <template #cell="{ record }">
                                <a-space size="mini">
                                    <a-link @click="openModal(record)">
                                        编辑
                                    </a-link>
                                    <a-popconfirm position="left" content="确定要删除这个方案吗？" @ok="handleDelete(record.id)">
                                        <a-link>
                                            删除
                                        </a-link>
                                    </a-popconfirm>
                                </a-space>
                            </template>
                        </a-table-column>
                    </template>
                </a-table>
            </a-space>
        </a-card>

        <a-modal v-model:visible="modalVisible" :title="formData.id ? '编辑方案' : '添加方案'" @before-ok="handleSubmit"
            @cancel="closeModal" :width="600">
            <a-form :model="formData" ref="formRef" layout="vertical">
                <a-form-item field="name" label="方案名称" :rules="[{ required: true, message: '请输入方案名称' }]">
                    <a-input v-model="formData.name" placeholder="请输入方案名称" />
                </a-form-item>
                <a-form-item label="图片" :rules="[{ required: true }]">
                    <a-upload list-type="picture" v-model="formData.image" :custom-request="handleUpload" :limit="1"
                        :file-list="fileList" image-preview @before-remove="beforeRemove" />
                    <template #extra>
                        <div>请保持图片比例为1.59:1（全球统一的通用规格），格式为jpg/png</div>
                    </template>
                </a-form-item>
                <a-form-item field="description" label="方案描述" :rules="[{ required: true, message: '请输入方案描述' }]">
                    <a-textarea v-model="formData.description" placeholder="请输入方案描述" :rows="3" />
                </a-form-item>
                <a-row :gutter="16">
                    <a-col :span="12">
                        <a-form-item field="money" label="方案金额" :rules="[{ required: true, message: '请输入方案金额' }]">
                            <a-input-number v-model="formData.money" placeholder="请输入方案金额" :precision="2" :min="0" style="width: 100%" />
                        </a-form-item>
                    </a-col>
                    <a-col :span="12">
                        <a-form-item field="days" label="方案天数" :rules="[{ required: true, message: '请输入方案天数' }]">
                            <a-input-number v-model="formData.days" placeholder="请输入方案天数" :min="1" style="width: 100%" />
                        </a-form-item>
                    </a-col>
                </a-row>
                <a-form-item field="status" label="状态">
                    <a-radio-group v-model="formData.status">
                        <a-radio value="online">上线</a-radio>
                        <a-radio value="offline">下线</a-radio>
                    </a-radio-group>
                </a-form-item>
            </a-form>
        </a-modal>

        <!-- VIP权益管理模态框 -->
        <a-modal v-model:visible="vipDetailModalVisible" title="VIP权益管理"
            @cancel="closeVipDetailModal" :width="800">
            <a-space fill direction="vertical">
                <a-row :gutter="16">
                    <a-col :span="24">
                        <a-space fill>
                            <a-button type="primary" @click="openVipDetailFormModal()" shape="round">
                                <template #icon><icon-plus /></template>
                                添加权益
                            </a-button>
                        </a-space>
                    </a-col>
                </a-row>

                <a-table :data="vipDetailRenderData" :loading="vipDetailLoading" :bordered="{ cell: true }" :pagination="vipDetailPagination"
                    @page-change="onVipDetailPageChange" draggable :scroll="{ x: 1200 }" @page-size-change="onVipDetailPageSizeChange">
                    <template #columns>
                        <a-table-column title="ID" data-index="id" :width="80" />
                        <a-table-column title="图标" data-index="icon" :width="100">
                            <template #cell="{ record }">
                                <a-image v-if="record.icon_url" :src="record.icon_url" width="40" height="40" />
                                <span v-else>-</span>
                            </template>
                        </a-table-column>
                        <a-table-column title="权益名称" data-index="name" />
                        <a-table-column title="副标题" data-index="sub_name" />
                        <a-table-column title="描述" data-index="description" />
                        <a-table-column title="创建时间" data-index="created_at" :width="180">
                            <template #cell="{ record }">
                                {{ formatTime(record.created_at) }}
                            </template>
                        </a-table-column>
                        <a-table-column title="更新时间" data-index="updated_at" :width="180">
                            <template #cell="{ record }">
                                {{ formatTime(record.updated_at) }}
                            </template>
                        </a-table-column>
                        <a-table-column title="操作" align="center" :width="120" fixed="right">
                            <template #cell="{ record }">
                                <a-space size="mini">
                                    <a-link @click="openVipDetailFormModal(record)">
                                        编辑
                                    </a-link>
                                    <a-popconfirm position="left" content="确定要删除这个权益吗？" @ok="handleVipDetailDelete(record.id)">
                                        <a-link>
                                            删除
                                        </a-link>
                                    </a-popconfirm>
                                </a-space>
                            </template>
                        </a-table-column>
                    </template>
                </a-table>
            </a-space>
        </a-modal>

        <!-- VIP权益表单模态框 -->
        <a-modal v-model:visible="vipDetailFormModalVisible" :title="vipDetailFormData.id ? '编辑权益' : '添加权益'" @before-ok="handleVipDetailFormSubmit"
            @cancel="closeVipDetailFormModal" :width="600">
            <a-form :model="vipDetailFormData" ref="vipDetailFormRef" layout="vertical">
                <a-form-item label="权益图标" :rules="[{ required: true, message: '请上传权益图标' }]">
                    <a-upload list-type="picture" v-model="vipDetailFormData.icon" :custom-request="handleVipDetailUpload" :limit="1"
                        :file-list="vipDetailFileList" image-preview @before-remove="beforeVipDetailRemove"/>
                    <template #extra>
                        <div>建议上传正方形图标，尺寸建议40x40px</div>
                    </template>
                </a-form-item>
                <a-form-item field="name" label="权益名称" :rules="[{ required: true, message: '请输入权益名称' }]">
                    <a-input v-model="vipDetailFormData.name" placeholder="请输入权益名称" />
                </a-form-item>
                <a-form-item field="sub_name" label="权益副标题" >
                    <a-input v-model="vipDetailFormData.sub_name" placeholder="请输入权益副标题" />
                </a-form-item>
                <a-form-item field="description" label="权益描述">
                    <a-textarea v-model="vipDetailFormData.description" placeholder="请输入权益描述" :rows="3" />
                </a-form-item>
            </a-form>
        </a-modal>
    </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue';
import { Message } from '@arco-design/web-vue';
import type { UploadRequest, RequestOption, FileItem } from '@arco-design/web-vue';
import useLoading from '@/hooks/loading';
import { Pagination } from '@/types/global';
import { 
    queryVipSolutionList, 
    submitVipSolutionForm, 
    delVipSolution, 
    VipSolutionRecord, 
    VipSolutionModel,
    queryVipDetailList,
    submitVipDetailForm,
    delVipDetail,
    VipDetailRecord,
    VipDetailModel
} from '@/api/vipSolution';
import { uploadFile } from '@/api/upload';

const { loading, setLoading } = useLoading(true);
const modalVisible = ref(false);
const formRef = ref();
const fileList = ref([]);

// VIP权益相关状态
const vipDetailModalVisible = ref(false);
const vipDetailFormModalVisible = ref(false);
const vipDetailFormRef = ref();
const vipDetailLoading = ref(false);
const vipDetailFileList = ref<{ url: string }[]>([]);

const basePagination = {
    current: 1,
    pageSize: 10,
    total: 0,
};

const pagination = reactive({
    ...basePagination,
});

// VIP权益分页
const vipDetailPagination = reactive({
    ...basePagination,
});

const generateFormData = () => {
    return {
        id: 0,
        name: '',
        description: '',
        money: 0,
        days: 30,
        status: 'online',
    };
};

// VIP权益表单数据生成函数
const generateVipDetailFormData = () => {
    return {
        id: 0,
        icon: '',
        name: '',
        sub_name: '',
        description: '',
        image: '',
    };
};

const formData = ref(generateFormData());
const vipDetailFormData = ref(generateVipDetailFormData());

const renderData = ref<VipSolutionRecord[]>([]);
const vipDetailRenderData = ref<VipDetailRecord[]>([]);

const fetchData = async () => {
    setLoading(true);
    try {
        const { data } = await queryVipSolutionList({
            page: pagination.current,
            pageSize: pagination.pageSize,
        });
        renderData.value = data.list;
        pagination.total = data.total;
    } catch (err) {
        Message.error('获取VIP方案列表失败');
    } finally {
        setLoading(false);
    }
};

const onPageChange = (current: number) => {
    pagination.current = current;
    fetchData();
};

const onPageSizeChange = (pageSize: number) => {
    pagination.pageSize = pageSize;
    pagination.current = 1;
    fetchData();
};

// VIP权益相关函数
const fetchVipDetailData = async () => {
    vipDetailLoading.value = true;
    try {
        const { data } = await queryVipDetailList({
            page: vipDetailPagination.current,
            pageSize: vipDetailPagination.pageSize,
        });
        vipDetailRenderData.value = data.list;
        vipDetailPagination.total = data.total;
    } catch (err) {
        Message.error('获取VIP权益列表失败');
    } finally {
        vipDetailLoading.value = false;
    }
};

const onVipDetailPageChange = (current: number) => {
    vipDetailPagination.current = current;
    fetchVipDetailData();
};

const onVipDetailPageSizeChange = (pageSize: number) => {
    vipDetailPagination.pageSize = pageSize;
    vipDetailPagination.current = 1;
    fetchVipDetailData();
};

const openModal = (record?: VipSolutionRecord) => {
    if (record) {
        formData.value = {
            id: record.id,
            name: record.name,
            description: record.description,
            money: record.money,
            days: record.days,
            status: record.status,
            image: record.image,
            image_url: record.image_url,
        };


        fileList.value = [{ uid: '1', url: record.image_url }];
    } else {
        formData.value = generateFormData();
        fileList.value = [];
    }
    modalVisible.value = true;
};

const closeModal = () => {
    modalVisible.value = false;
    formData.value = generateFormData();
};

// VIP权益模态框相关函数
const openVipDetailModal = () => {
    vipDetailModalVisible.value = true;
    fetchVipDetailData();
};

const closeVipDetailModal = () => {
    vipDetailModalVisible.value = false;
};

const openVipDetailFormModal = (record?: VipDetailRecord) => {
    if (record) {
        vipDetailFormData.value = {
            id: record.id,
            icon: record.icon,
            name: record.name,
            sub_name: record.sub_name,
            description: record.description,
        };
        vipDetailFileList.value = record.icon ? [{ url: record.icon }] : [];
    } else {
        vipDetailFormData.value = generateVipDetailFormData();
        vipDetailFileList.value = [];
    }
    vipDetailFormModalVisible.value = true;
};

const closeVipDetailFormModal = () => {
    vipDetailFormModalVisible.value = false;
    vipDetailFormData.value = generateVipDetailFormData();
    vipDetailFileList.value = [];
};


const handleUpload = (option: any): UploadRequest => {
	try {
		const { onProgress, onError, onSuccess, fileItem } = option;

		const uploadFormData = new FormData();
		uploadFormData.append('file', fileItem.file);
		
		uploadFile(uploadFormData).then(({ data }) => {
			formData.value.image = data.path;
			fileList.value = [{ url: data.url } as FileItem];

			Message.success('上传成功');
		}).catch((err) => {
			Message.error('上传失败');
		});

		return {
			abort: () => { },
		};
	} catch (err) {
		Message.error('上传失败');
		return {
			abort: () => { },
		};
	}
};

const beforeRemove = async (fileItem: FileItem): Promise<boolean> => {
	formData.value.image = '';
	fileList.value = [];
	return true;
};

const handleSubmit = async (done: any) => {
    setLoading(true);
    try {
        await submitVipSolutionForm(formData.value).then((res) => {
            Message.success(res.msg || '操作成功');
            closeModal();
            fetchData();
            done(true);
        });
    } catch (err) {
        done(false);
    } finally {
        setLoading(false);
    }
};

const handleDelete = async (id: number) => {
    try {
        await delVipSolution(id);
        Message.success('删除成功');
        fetchData();
    } catch (err) {
        Message.error('删除失败');
    }
};

// VIP权益相关处理函数
const handleVipDetailUpload = async (option: any) => {
    try {
        const { onProgress, onError, onSuccess, fileItem, name } = option;

        const uploadFormData = new FormData();
        uploadFormData.append('file', fileItem.file);
        const { data } = await uploadFile(uploadFormData);
        vipDetailFormData.value.icon = data.path;
        vipDetailFileList.value = [{ url: data.url }];
        Message.success('上传成功');
        return {
            abort: () => { },
        };
    } catch (err) {
        Message.error('上传失败');
        return {
            abort: () => { },
        };
    }
};

const beforeVipDetailRemove = (file: any) => {
    vipDetailFormData.value.icon = '';
    vipDetailFileList.value = [];
    return true;
};

const handleVipDetailFormSubmit = async (done: any) => {
    try {
        await submitVipDetailForm(vipDetailFormData.value).then((res) => {
            Message.success(res.msg || '操作成功');
            closeVipDetailFormModal();
            fetchVipDetailData();
            done(true);
        });
    } catch (err) {
        done(false);
    }
};

const handleVipDetailDelete = async (id: number) => {
    try {
        await delVipDetail(id);
        Message.success('删除成功');
        fetchVipDetailData();
    } catch (err) {
        Message.error('删除失败');
    }
};

const formatTime = (timestamp: number) => {
    if (!timestamp) return '-';
    const date = new Date(timestamp * 1000);
    return date.toLocaleString('zh-CN');
};

onMounted(() => {
    fetchData();
});
</script>
